package com.agent.util;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 工具类
 */
public class AppUtil {
    public static String serverIp(){
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
           return "127.0.0.1";
        }
        return localHost.getHostAddress();
    }
    public static String getAppName() {
        String command = System.getProperty("sun.java.command", "");
        if (command == null || command.isEmpty()){
            return "Unknown";
        }
        // 场景 1: -jar 方式启动 (java -jar app.jar)
        if (command.contains("-jar")) {
            String[] parts = command.split("\\s+");
            for (int i = 0; i < parts.length; i++) {
                if ("-jar".equals(parts[i]) && i + 1 < parts.length) {
                    return extractNameFromJar(parts[i + 1]);
                }
            }
        }
        // 场景 2: 直接执行主类 (java com.example.Main)
        else {
            String[] parts = command.split("\\s+");
            for (String part : parts) {
                if (!part.startsWith("-")) {
                    return part.split("\\s+")[0];
                }
            }
        }
        return "Unknown";
    }

    private static String extractNameFromJar(String jarPath) {
        String fileName = new File(jarPath).getName();
        if (fileName.endsWith(".jar")) {
            return fileName.substring(0, fileName.length() - 4);
        }
        return fileName;
    }
}